//
//  ViewController.m
//  PhotoTag
//
//  Created by Andrew on 2018/8/2.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "ViewController.h"
#import "SDPhotoBrowser.h"
#import "YMImageCell.h"
#import "ZZPhotoKit.h"
#import "ImageArrModel.h"
#import <MJExtension.h>

@interface ViewController () <UICollectionViewDelegate,UICollectionViewDataSource,SDPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;//添加图片,每个cell内有一个imageView
/* 图片数据 */
@property (nonatomic, strong) NSMutableArray *imageArray;


@end

@implementation ViewController

static NSString *collectionViewCellId = @"YMImageCell";
static CGFloat imageSize = 80;
//设置可选最多图片
#define CanChooseImage 9

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setCollectionView];
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadCollectionView:) name:PostImagesNotifi object:nil];
}

- (void)reloadCollectionView:(NSNotification *)info
{
    NSArray *arr = info.userInfo[@"imageSource"];
    [self.imageArray addObjectsFromArray:arr];
    [self.collectionView reloadData];
}

#pragma mark  设置CollectionView
- (void)setCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(imageSize + 10, imageSize + 10);
    
    //滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 74, SCREENWIDTH, 500) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YMImageCell class]) bundle:nil] forCellWithReuseIdentifier:collectionViewCellId];
}

#pragma mark - UIImagePickerControllerDelegate
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YMImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellId forIndexPath:indexPath];
    
    //判断是否是加号
    if (self.imageArray.count == indexPath.row) {
        cell.isAddImageBtn = YES;
    }
    if (self.imageArray.count && !(self.imageArray.count == indexPath.row)) {
        cell.photo = self.imageArray[indexPath.row];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //如果是加号
    if (self.imageArray.count == indexPath.row) {
        [self selectedAddBtnClickEvent];
    } else {
        //点击图片
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.sourceImagesContainerView = collectionView;
        browser.imageCount = self.imageArray.count;
        browser.imageModels = self.imageArray;
        browser.currentImageIndex = indexPath.row;
        browser.delegate = self;
        [browser show];
    }
}

// 返回临时占位图片（即原来的小图）
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    NSMutableArray *arr = [NSMutableArray new];
    for (ImageArrModel *photo in self.imageArray) {
        [arr addObject:photo.image];
    }
    return arr[index];
}

- (void)selectedAddBtnClickEvent
{
    WS(ws);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws setupImagePickerController:UIImagePickerControllerSourceTypeCamera];
    }];
    
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws chooseAlbum];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:camera];
    [alert addAction:album];
    [alert addAction:cancel];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(imageSize, imageSize);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 25, 0, 25);
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

- (void)setupImagePickerController:(UIImagePickerControllerSourceType)type
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = type;
    [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}

#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //定义一个newPhoto，用来存放我们选择的图片。
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    UIImage *newPhoto = [[UIImage alloc] init];
    if ([mediaType isEqualToString:@"public.image"])
    {
        newPhoto = info[@"UIImagePickerControllerOriginalImage"];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)chooseAlbum
{
    ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
    photoController.selectPhotoOfMax = CanChooseImage;
    //设置相册中完成按钮旁边小圆点颜色。
    photoController.roundColor = [UIColor greenColor];
    
    WS(ws);
    [photoController showIn:self result:^(id responseObject){
        
//        NSMutableArray *imageArr = [NSMutableArray new];
//        [imageArr addObjectsFromArray:responseObject];
//        
//        [ws.imageArray addObjectsFromArray:imageArr];
//        [ws.collectionView reloadData];
    }];
}

#pragma mark - 懒加载
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray new];
    }
    return _imageArray;
}


@end
